import path from "path"
import { defineConfig } from "vite"
import vue from "@vitejs/plugin-vue"
import vueDevTools from "vite-plugin-vue-devtools"
import AutoImports from "unplugin-auto-import/vite"
import Components from "unplugin-vue-components/vite"
import PurchasingComponentsResolver from "@purchasing/components/resolver"
import dts from "vite-plugin-dts"

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
  plugins: [
    vue(),
    vueDevTools(),
    AutoImports({
      imports: ["vue", "vue-router"],
      eslintrc: { enabled: true },
    }),
    Components({
      resolvers: [PurchasingComponentsResolver()],
    }),
    dts({ tsconfigPath: "tsconfig.app.json", rollupTypes: true }),
  ],
  server: {
    proxy: {
      "/api/resources": {
        bypass(req, res) {
          const params = new URL(req.url!, "http://localhost:5173")
            .searchParams as any

          const keyword = params.get("keyword")
          const pagination = {
            page: parseInt(params.get("page")),
            size: parseInt(params.get("size")),
          }

          const content = [...Array(pagination.size).keys()].map((index) => {
            const id = (pagination.page - 1) * pagination.size + index + 1
            return {
              id,
              property1: (keyword || "propertyOne") + id,
              property2: (keyword || "propertyTwo") + id,
            }
          })

          res.end(
            JSON.stringify({
              content: content,
              page: pagination.page,
              size: pagination.size,
              total: 100,
            }),
          )

          if (req.url?.includes("export")) {
            res.end(JSON.stringify(content))
          }

          return false
        },
      },
      "/api/export": {
        bypass(_, res) {
          const keyword = "hello world"
          const pagination = { size: 10, page: 1 }
          const content = [...Array(pagination.size).keys()].map((index) => {
            const id = (pagination.page - 1) * pagination.size + index + 1
            return {
              id,
              property1: (keyword || "propertyOne") + id,
              property2: (keyword || "propertyTwo") + id,
            }
          })
          res.end(JSON.stringify(content))
        },
      },
    },
  },
})
